import {ref, onMounted, onUnmounted, Ref, reactive} from 'vue'
import Engine, {EngineInterface, CardToolbarInterface} from '@aomao/engine'
import AmToolbar, {ToolbarPlugin, ToolbarComponent} from '@/plugins/editor/toolbar'
import CodeBlock, {CodeBlockComponent} from '@/plugins/editor/codeblock';
import Heading from '@aomao/plugin-heading'
import Bold from '@aomao/plugin-bold'
import Quote from '@aomao/plugin-quote'
import FontColor from '@aomao/plugin-fontcolor'
import Code from '@aomao/plugin-code'
import Redo from '@aomao/plugin-redo'
import Undo from '@aomao/plugin-undo'
import Alignment from '@aomao/plugin-alignment'
import TaskList, {CheckboxComponent} from '@aomao/plugin-tasklist';
import UnOrderedList from '@aomao/plugin-unorderedlist'
import OrderList from '@aomao/plugin-orderedlist'
import Table, {TableComponent} from '@aomao/plugin-table';
import Link from '@/plugins/editor/link';

const plugins = [
    ToolbarPlugin,
    Heading,
    Bold,
    Quote,
    FontColor,
    Code,
    Redo,
    Undo,
    Alignment,
    CodeBlock,
    TaskList,
    UnOrderedList,
    OrderList,
    Table,
    Link
]
const cards = [
    ToolbarComponent,
    CodeBlockComponent,
    TableComponent,
    CheckboxComponent
]

export default function () {
    const toolbarItems = reactive([['collapse'],
        ['undo', 'redo', 'paintformat', 'removeformat'],
        ['heading', 'fontsize'],
        [
            'bold',
            'italic',
            'strikethrough',
            'underline',
            'moremark',
        ],
        ['fontcolor', 'backcolor'],
        ['alignment'],
        ['unorderedlist', 'orderedlist', 'tasklist', 'indent'],
        ['link', 'quote', 'hr'],]);

    const editorContainer = ref<HTMLElement | null>(null);
    const engine = ref<EngineInterface | null>(null);
    onMounted(() => {
        if (editorContainer.value) {
            engine.value = new Engine(editorContainer.value, {
                plugins, cards
            });

            const engineInstance = engine.value
            /*engineInstance.messageSuccess = (msg: string) => {
              console.log(msg)
            };
            engineInstance.messageError = (error: string) => {
              console.error(error);
            };*/
            //初始化本地协作，用作记录历史
            engineInstance.ot.initLockMode();

            //设置编辑器值
            engineInstance.setValue("<strong>我在这里哟～</strong>")
            //监听编辑器值改变事件
            engineInstance.on('change', value => {
                // console.log('value', value);
                // console.log('html:', engineInstance.getHtml());
            });
        }
    })
    onUnmounted(() => {
        if (engine.value)
            engine.value.destroy();

    })
    return {
        engine,
        editorContainer,
        toolbarItems
    }

}
export {AmToolbar}
